//
//  XS_VerificationCodeVC.swift
//  XueDao
//
//  Created by 韩云智 on 2020/12/4.
//

import UIKit
import RxCocoa
import RxSwift

class XS_VerificationCodeVC: XS_BaseVC {
    
    var openid: String?
    var iosid: String?

    //是否是绑定
    var isBind : Bool = false
    
    var reuseDisposeBag = DisposeBag()
    lazy var phone = ""
    lazy var code = ""
    
    override func upView() {
        let lab = UILabel.xsLabel(size: .scale*22, fontName: .medium, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: "输入验证码")
        view.addSubview(lab)
        lab.snp.makeConstraints { m in
            m.top.equalTo(.scale*13)
            m.left.equalTo(.scale*16)
        }
        
        let dLab = UILabel.xsLabel(size: .scale*16, fontName: .medium, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), text: "已发送至 " + phone.cipher(pre: 3, suf: 4))
        view.addSubview(dLab)
        dLab.snp.makeConstraints { m in
            m.top.equalTo(lab.snp.bottom).offset(.scale*21)
            m.left.equalTo(.scale*16)
        }
        
        let button = XS_NoHighlightBtn()
        button.layer.cornerRadius = .scale*16
        button.layer.backgroundColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 0.1)
        button.setTitle("  重新获取  ", for: .normal)
        button.setTitleColor(#colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1), for: .normal)
        button.setTitleColor(#colorLiteral(red: 0.768627451, green: 0.7764705882, blue: 0.8039215686, alpha: 1), for: .disabled)
        button.titleLabel?.font = .xsFont(name: .regular, .scale*14)
        view.addSubview(button)
        button.snp.makeConstraints { m in
            m.height.equalTo(.scale*32)
            m.centerY.equalTo(dLab.snp.centerY)
            m.right.equalTo(-.scale*16)
        }
        
        let time = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.asyncInstance)
        button.rx.tap.asDriver()
            .startWith(())
            .throttle(.seconds(1), latest: false)
            .drive(onNext: { [weak self] in
                button.setTitle("  重新获取(60)  ", for: .disabled)
                button.isEnabled = false
                button.layer.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.7764705882, blue: 0.8039215686, alpha: 0.1)
                
                guard let `self` = self else { return }
                XS_NetWork.requestJson("/user/send", parameters: ["phone":self.phone])
                    .subscribe()
                    .disposed(by: self.disposeBag)
                self.reuseDisposeBag = DisposeBag()
                time.subscribe(onNext: { [weak self] index in
                    guard let `self` = self else { return }
                    if index < 60 {
                        button.setTitle("  重新获取(\(59-index)  ", for: .disabled)
                    } else {
                        self.reuseDisposeBag = DisposeBag()
                        button.isEnabled = true
                        button.layer.backgroundColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 0.1)
                    }
                }).disposed(by: self.reuseDisposeBag)
            }).disposed(by: disposeBag)
        
        let sure = XS_NoHighlightBtn()
        sure.frame = CGRect(x: .scale*48, y: .scale*315, width: .scale*279, height: .scale*48)
        sure.layer.cornerRadius = .scale*24
        sure.layer.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.7764705882, blue: 0.8039215686, alpha: 1)
        sure.isUserInteractionEnabled = false
        sure.setTitle("确定", for: .normal)
        sure.setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal)
        sure.titleLabel?.font = .xsFont(name: .medium, .scale*16)
        view.addSubview(sure)
        sure.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                guard let `self` = self else { return }
                var parameters: [String:Any] = ["phone" : self.phone, "code":self.code]
                if let openid = self.openid {
                    parameters["openid"] = openid
                }
                if let iosid = self.iosid {
                    parameters["iosid"] = iosid
                }
                if let paste = UIPasteboard.general.string {
                    
                }
                if self.isBind {
                    XS_NetWork.requestJson("/user/updateUserPhone",parameters: parameters)
                        .subscribe(onNext: { resp in //直接返回原始数据 resp.data
                            if resp.success{
                                let token = resp.data as! String
                                XS_Singleton.shared.infoModel?.token = token
                                        XS_Singleton.shared.infoModel = XS_Singleton.shared.infoModel
                                self.navigationController?.popToRootViewController(animated: true)
                            }
                            else{
                                self.view.makeToast(resp.msg)
                            }
                        }).disposed(by: self.disposeBag)
                }else{
                    XS_NetWork.requestJson("/user/codeRegister", parameters: parameters)
                        .mapModel(type: XS_UserInfoM.self)
                        .subscribe(onNext: { [weak self] model, resp in
                            self?.view.makeToast(resp.msg)
                            guard resp.success, let model = model else { return }
                            XS_Singleton.shared.infoModel = model
                            if (model.isAnswer != 0) {
                                self?.navigationController?.popToRootViewController(animated: true)
                            } else {
                                let vc = XS_Q1VC()
                                vc.title = "问题1，共3个"
                                vc.text = "您的就业方向是什么？"
                                vc.desc = "请回答下列问题，方便我们为您量身定制课程计划。"
                                self?.navigationController?.pushViewController(vc, animated: true)
                            }
                        }).disposed(by: self.disposeBag)
                }
                
            }).disposed(by: disposeBag)
        
        let config = JHVCConfig()
        config.autoShowKeyboard = true
        config.inputBoxNumber  = 4
        config.inputBoxSpacing = .scale*29
        config.inputBoxWidth   = .scale*48
        config.inputBoxHeight  = .scale*64
        config.tintColor       = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
        config.secureTextEntry = false
        config.inputBoxColor   = #colorLiteral(red: 0.9019607843, green: 0.9137254902, blue: 0.9450980392, alpha: 1)
        config.font            = .xsFont(name: .medium, .scale*22)
        config.textColor       = #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        config.inputType       = .number
        config.inputBoxBorderWidth = .scale
        config.inputBoxCornerRadius = .scale*10
        config.keyboardType = .numberPad
        
        
        if let codeView = JHVerificationCodeView(frame: CGRect(x: .scale*48, y: .scale*158, width: .screenWidth - .scale*48*2, height: .scale*64), config: config) {
            codeView.inputBlock = { code in
                guard let code = code else { return }
                if code.count < 4 {
                    sure.layer.backgroundColor = #colorLiteral(red: 0.768627451, green: 0.7764705882, blue: 0.8039215686, alpha: 1)
                    sure.isUserInteractionEnabled = false
                } else {
                    sure.layer.backgroundColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
                    sure.isUserInteractionEnabled = true
                }
            }
            codeView.finishBlock = { [weak self] codeView, code in
                guard let `self` = self, let code = code else { return }
                self.code = code
            }
            view.addSubview(codeView)
        }
    }
}
